package com.tsfyun.common.base.validator;

import com.tsfyun.common.base.annotation.LengthTrim;
import com.tsfyun.common.base.util.StringUtils;
import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Collection;
import java.util.Objects;

/**
 * Created by Rick on 2020/3/7.
 *
 * @ Description：
 */
@Slf4j
public class LengthTrimValidator implements ConstraintValidator<LengthTrim, Object> {

    private int min;

    private int max;

    @Override
    public void initialize(LengthTrim lengthTrim) {
        min = lengthTrim.min();
        max = lengthTrim.max();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
        if (value instanceof String) {
            String trimVal = StringUtils.null2EmptyWithTrim(value);
            if (StringUtils.isNotEmpty(trimVal)) {
                return trimVal.length() >= min && trimVal.length() <= max;
            }
            return true;
        } else if (value instanceof Collection) {
            if (Objects.isNull(value)) {
                return true;
            }
            return Objects.nonNull(value) && ((Collection) value).size() >= min && ((Collection) value).size() <= max;
        } else {
            String trimVal = StringUtils.null2EmptyWithTrim(value);
            if (StringUtils.isNotEmpty(trimVal)) {
                return trimVal.length() >= min && trimVal.length() <= max;
            }
            return true;
        }
    }
}
